package com.jn.mvvm2.model;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.jn.mvvm2.entity.Pet;
import com.jn.mvvm2.service.PetRepository;

import java.util.ArrayList;
import java.util.List;

public class PetViewModel extends ViewModel {
    private static final String TAG = "PetViewModel";

    private PetRepository petRepository;
    private MutableLiveData<List<Pet.PetDetails>> pets;
    private List<Pet.PetDetails> allPets; // 用于存储完整的宠物数据
    private MutableLiveData<Pet.PetDetails> selectedPet;
    private String url;

    public PetViewModel() {
        petRepository = new PetRepository();
        pets = new MutableLiveData<>();
        selectedPet = new MutableLiveData<>();
    }

    public LiveData<List<Pet.PetDetails>> getPets() {
        return pets;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void fetchPets(String type, String page, String num, String name) {
        petRepository.getPets(url, type, page, num, name, new PetRepository.PetCallback() {
            @Override
            public void onSuccess(List<Pet.PetDetails> petList) {
                Log.d(TAG, "成功获取宠物数据: " + petList.size());
                allPets = petList; // 保存完整的宠物数据
                pets.setValue(petList);
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e(TAG, "获取宠物数据失败: " + errorMessage);
            }
        });
    }

    // 实现本地搜索
    public void searchPets(String query) {
        if (allPets != null) {
            List<Pet.PetDetails> filteredList = new ArrayList<>();
            for (Pet.PetDetails pet : allPets) {
                if (pet.getName().toLowerCase().contains(query.toLowerCase())) { // 假设宠物有getName方法
                    filteredList.add(pet);
                }
            }
            pets.setValue(filteredList); // 更新过滤后的列表
        }
    }
}
